<?php
//此控制器为用户登录后的控制器，实现用户登录后，对相对用户的购物车，订单，管理收货地址，修改密码等操作；
namespace Home\Controller;
use Common\Controller\QianController;
class UserController extends QianController{
	public function _initialize(){//
		parent::_initialize();//本身被此页面使用，同时继承QianController里面的函数；
		//***********************************
		$r=$this->getCateByPid();
        $this->assign('top_banner_left',$r);
        //***********************************
        $this->assign('index',U('Index/Index'));
        $this->assign('productlist',U('Index/ProductList'));
		$this->assign('logout',U('Login/logout'));//user控制器退出登录
		$this->assign('myorder',U('Myorder'));//各个网页进入订单页面
        $this->assign('usermessage',U('UserMessage'));//各个网页进入用户信息
        $this->assign('address',U('Address'));//各个网页进入用户收货地址管理页面
        $this->assign('buycar',U('Buycar'));//各个网页进入购物车页面EditPassword
        $this->assign('editpassword',U('EditPassword'));//各个网页修改密码
        $this->assign('buy',U('Index/Index'));//继续购物
        $this->assign('pay',U('User/Pay'));//继续购物
        header('Content-type:text/html;charset=utf-8');

	}
//******************************************************************************************************
	public function getCateByPid ($pid=0){//递归函数去值
		$user=M('Category');
		$result=$user->where("status=1 and precategory={$pid}")->select();
		if(!empty($result)){
			foreach ($result as $key => $value) {
				$result[$key]['child']=$this->getCateByPid($value['id']);
			}
		}
		return $result;
    }
//******************************************************************************************************
	public function Myorder(){//点击进入用户订单界面；
        layout('order');
        $this->assign('delorder',U('Delorder'));//取消订单页面
        $this->assign('deleterorder',U('Deleterorder'));//取消订单页面
        $this->assign('finish',U('Finish'));//订单页立即付款页面
        $loginuser_id=$this->user_id;//登录时，用户地ID
        $user=M('myorder');
        $r=$user->where("loginuser_id='{$loginuser_id}'")->select();
        foreach ($r as $key => $value) {
            $aaa=M('goods_order');
            $r[$key]['goods']=$aaa->where("order_id='{$value['id']}'")->select();
        }
        // print_r($r);
        // exit;
        $this->assign('order',$r);
        $this->display();
	}
//********************************取消订单**********************************************************
    public function Delorder(){
        if(IS_AJAX){
            // exit;
            $ordercode=I('post.ordercode');
            $user=M('myorder');
            $data['status']='4';
            $r=$user->where("ordercode='{$ordercode}'")->save($data);
            if($r){
                $this->ajaxreturn(array('code'=>'666','msg'=>'取消成功'));
            }else{
                $this->ajaxreturn(array('code'=>'000','msg'=>'取消失败'));
            }
        }
    }
//********************************订单被用户取消后有个删除按钮，来删除订单********************
    public function Deleterorder(){
        if(IS_GET){
            if(!is_null(I('get.deletercode'))){
                $ordercode=I('get.deletercode');
                $user=M('myorder');
                $user->startTrans();//开启事务
                $r=$user->where("ordercode='{$ordercode}'")->find();
                $id=$r['id'];//订单ID
                $go=M('goods_order');
                $re=$go->where("order_id='{$id}'")->delete();
                if($re){
                    $r=$user->where("ordercode='{$ordercode}'")->delete();
                    if($r){
                        $user->commit();
                        header("location:Myorder");
                    }else{
                        $user->rollback();
                        $this->error('删除订单失败');
                    }
                }else{
                    $user->rollback();
                    $this->error('删除失败');
                }
            }
        }

    }
//*********************************************************************************************
	public function Address(){//进入用户管理收货地址页面
        layout('order');
        $loginuser_id=$this->user_id;//登录时，用户地ID
        $this->action=U('AddressSave');
        $this->assign('deladdress',U('DelAddress'));
        $regionModel = M('region');
        $user=M('goodsuser');
        $this->states = $regionModel->where('pid=1')->select();
        $this->areas = $regionModel->where('pid=2')->select();
        $this->locals = $regionModel->where('pid=33')->select();
        $this->region = U('region');
        //如果没有保单操作，该页面显示以前保存过的收货人的信息
        $user=M('goodsuser');
        $message=$user->where("loginuser_id='{$loginuser_id}'")->select();
        $this->assign('message',$message);
        $this->display();
        // $this->display();
    }
//******************************************************************************************************
    public function region(){
        if(IS_AJAX){
            $pid=I('post.pid',0,'intval');
            if($pid>0){
                $regionModel = M('region');
                $data['status']='OK';
                $data['area'] = $regionModel->where('pid='.$pid)->select();
                $this->ajaxReturn($data);
            }
        }
    }
//******************************************************************************************************
    public function AddressSave(){
        $loginuser_id=$this->user_id;//登录时，用户地ID
        if(IS_POST){
            $p=I('post.province');
            $c=I('post.city');
            $a=I('post.area');
            $user=M('region');
            $p=$user->where("id='{$p}'")->getField('name');//省份、、string类型
            $c=$user->where("id='{$c}'")->getField('name');//市县
            $a=$user->where("id='{$a}'")->getField('name');//县区
            $goodsuser=D('goodsuser');
            $data=array(
                'loginuser_id'=>$loginuser_id,
                'province'=>$p,
                'city'=>$c,
                'area'=>$a,
                'detailsaddress'=>I('post.detailsaddress'),
                'buyusername'=>I('post.buyusername'),
                'gender'=>I('post.gender'),
                'code'=>I('post.code'),
                'email'=>I('post.email'),
                'phone'=>I('post.phone'),
                'telphone'=>I('post.telphone'),
                'add_time'=>date("Y-m-d H:i:s",time())
                );
            if($goodsuser->create()){
                if($goodsuser->add($data)){
                    header("location:".U('Address'));
                }else{
                    $this->error($goodsuser->getError());
                }
            }else{
                $this->error($goodsuser->getError());
            }

        }
    }
//******************************************************************************************************
    public function UserMessage(){
        layout('order');
        $loginuser_id=$this->user_id;//登录时，保存的用户ID
        $user=M('loginuser');
        $message=$user->where("id='{$loginuser_id}'")->find();
        $this->assign('r',$message);
        // print_r($r);
        // exit;
        $this->display();
    }
//******************************************************************************************************
    public function EditPassword(){
        layout('order');
        $this->assign('act',U('ajax'));
        $this->display();
    }
//******************************************************************************************************
    public function ajax(){
        if(IS_AJAX){
            if(empty(I('post.oldpassword'))){
                $this->ajaxreturn(array('code'=>'001','msg'=>'请输入原密码'));
            }
            if(empty(I('post.newpassword'))){
                $this->ajaxreturn(array('code'=>'001','msg'=>'请输入新密码'));
            }
            if(empty(I('post.newpassword1'))){
                $this->ajaxreturn(array('code'=>'001','msg'=>'请输入确认新密码'));
            }
            $pass1=addslashes(I('post.newpassword'));
            $pass2=addslashes(I('post.newpassword1'));
            if($pass1!=$pass2){
                $this->ajaxreturn(array('code'=>'001','msg'=>'两次密码不一样'));
            }
            
            $loginuser_id=$this->user_id;//登录时，保存的用户ID
            $user=M('loginuser');
            $message=$user->where("id='{$loginuser_id}'")->find();
            if($message['password']!=I('post.oldpassword')){
                $this->ajaxreturn(array('code'=>'001','msg'=>'原密码错误'));
            }
            if(!preg_match('/^[A-Za-z0-9]{6,10}$/', $pass1)){
                $this->ajaxreturn(array('code'=>'001','msg'=>'请输入有英文和数字组成的密码'));
            }
            $data=array('password'=>$pass1);
            $r=$user->where("id={$loginuser_id}")->save($data);
            if($r){
                $this->ajaxreturn(array('code'=>'666','msg'=>'修改成功'));
            }
        }
    }
//******************************************************************************************************
    public function DelAddress(){
        // $loginuser_id=$this->user_id;//登录时，保存的用户ID
        if(!is_null(I('get.deladdressid'))){
            $deladdressid=I('get.deladdressid');
            $address=M('goodsuser');
            $r=$address->where("id='{$deladdressid}'")->delete();
                if($r){
                header("location:Address");
            }else{
                $this->error('操作失败');
            }
        }    
    }
//******************************************************************************************************
    public function Buycar(){
        layout('user');
        $loginuser_id=$this->user_id;//登录时，保存的用户ID
        $this->assign('buynum',U('Buynum'));//更新购物车的购买数量
        $this->assign('movecar',U('Movecar'));//移除购物车
        $this->assign('buynow',U('Buynow'));//立刻购买
        $this->assign('buysome',U('Buysome'));//一次购买多个
        $loginuser_id=$this->user_id;//登录时，保存的用户ID
        $user=M('buycar');
        $goods_id=array();
        $goods=$user->where("loginuser_id='{$loginuser_id}'")->select();
        // print_r($goods);
        // exit;
        foreach ($goods as $key => $value) {
            $goods_id[]=$value['goods_id'];
        }
        if(!empty($goods_id)){
            $goodsid=implode(',', $goods_id);//OK
            $g=M('goods');
            $goods=$g->field('*,(select name from fm_photo where fm_goods.id=fm_photo.goods_id limit 1) as name ')->join('right join fm_buycar on fm_goods.id=fm_buycar.goods_id')->where("fm_goods.id in ({$goodsid}) and loginuser_id='{$loginuser_id}'")->select();
            // print_r($goods);
            // exit;
            $pay=array();
            $this->assign('goods',$goods);
            foreach ($goods as $key => $value) {
                $pay[]=$value['totalpay'];
            }
            $totalpay=array_sum($pay);//购物车商品总价钱
            $this->assign('totalpay',$totalpay);
        }else{
            $goods=array();
            $this->assign('goods',$goods);
            $this->assign('totalpay','0');
        }
        $this->display();
    }
//******************************************************************************************************
    public function Buynum(){
        // exit;
        if(IS_AJAX){
            $goodsid=I('post.goodsid');
            $buynum=I('post.buynum');
            $totalpay=I('post.totalpay');
            $user=M('buycar');
            $data['buynum']=$buynum;
            $data['totalpay']=$totalpay;
            $r=$user->where("goods_id='{$goodsid}'")->save($data);
            if($r){
                $this->ajaxreturn(array('code'=>'666','msg'=>'更新成功'));
            }else{
                $this->ajaxreturn(array('code'=>'000','msg'=>'更新失败'));
            }
        }
    }
//******************************************************************************************************
    public function Movecar(){
        if(IS_AJAX){
            $buycarid=I('post.buycarid');           
            $user=M('buycar');
            $r=$user->where("id='{$buycarid}'")->delete();
            if($r){
                $this->ajaxreturn(array('code'=>'666','msg'=>'删除成功'));
            }else{
                $this->ajaxreturn(array('code'=>'000','msg'=>'删除失败'));
            }
        }  
    }

//******************************************************************************************************
    public function Buysome(){
        layout('user');
        $this->assign("finishsave",U('Finishsave'));
        $this->assign("addplace",U('Address'));
        $loginuser_id=$this->user_id;//登录时，保存的用户ID
        if(IS_POST){
            $buycarid=I('post.buycarid');//数组形式传过来。buycar表中的id
            // print_r($buycarid);
            // exit;

            if(empty($buycarid)){
                $this->error('请选择商品');
            }
            foreach ($buycarid as $key => $value) {
                $user=M('buycar');
                $r[]=$user->where("id={$value} and loginuser_id='{$loginuser_id}'")->find();
            }

            foreach ($r as $key => $value) {
                $g=M('goods');
                $r[$key]['goods']=$g->field('fm_goods.*,(select name from fm_photo where fm_goods.id=fm_photo.goods_id limit 1) as name ')->where("fm_goods.id={$value['goods_id']}")->find();
            }
            // print_r($r);
            // exit;
            $pay=array();
            foreach ($r as $key => $value) {//确认订单页面总金额
                $pay[]=$value['totalpay'];
            }
            $pay=array_sum($pay);
            $this->assign('total',$pay);
            $this->assign('buysome',$r);
            $address=M('goodsuser');//收货地址表
            $addr=$address->where("loginuser_id='{$loginuser_id}'")->select();
            $this->assign('address',$addr);
            $this->display();
        }
    }

//******************************************************************************************************
    public function Finishsave(){
        layout('false');
        $loginuser_id=$this->user_id;//登录时，保存的用户ID
        if(IS_POST){
            $buycar_id=I('post.buycarid');//购物车里面的ID。数组形式
            $address_id=I('post.addressid');//收货地址的ID
            $usermessage=I('post.usermessage');//买家留言
            // print_r($_POST);
            // exit;
            if(empty($buycar_id)){
                $this->error('操作失败');
            }
            if($address_id<1){
                $this->error('请选择收货地址');
            }
            $ordercode=mb_substr(date("l"),0,1).$loginuser_id.time();//生成订单号。
            foreach ($buycar_id as $key => $value) {
                $buycar[]=M("buycar")->where("id={$value}")->find();
            }
            // exit;
            foreach ($buycar as $key => $value) {
                $user=M('goods');
                $buycar[$key]['goods']=$user->field('fm_goods.*,(select name from fm_photo where fm_goods.id=fm_photo.goods_id limit 1) as name ')->where("fm_goods.id='{$value['goods_id']}'")->find();
            }
            foreach ($buycar as $key => $value) {
                $pay[]=$value['totalpay'];
            }
            // print_r($buycar);
            // exit;
            $totalpay=array_sum($pay);//订单总金额
            $addr=M('goodsuser');
            $row=$addr->where("id='{$address_id}'")->find();
            // print_r($row);
            // exit;
            $data=array(
                'loginuser_id'=>$loginuser_id,
                'ordercode'=>$ordercode,
                'add_time'=>date('Y-m-d H:i:s',time()),
                'totalpay'=>$totalpay,
                'buyusername'=>$row['buyusername'],
                'newaddress'=>$row['province'].'-'.$row['city'].'-'.$row['area'].'-'.$row['detailsaddress'],
                'usermessage'=>$usermessage
                );
            $order=M('myorder');
            $result=$order->add($data);
            $arr=array();
            if($result){
                foreach ($buycar as $key => $value) {
                    $arr=array(
                    'order_id'=>$result,
                    'goodsname'=>$value['goods']['goodsname'],
                    'price'=>$value['goods']['price'],
                    'buynum'=>$value['buynum'],
                    'totalpay'=>$value['totalpay'],
                    'photo'=>$value['goods']['name']
                    );
                    $goods_order=M('goods_order');
                    $to=$goods_order->add($arr);
                }
                
                    if($to){
                        // echo  $to;
                        // exit;
                        header("location:Finish?orderid=".$result);
                    }else{
                        $this->error("加入订单-商品表失败");
                    } 
            }else{
                $this->error('加入订单失败');
            }
            }else{
                 $this->error('操作失败');
            }
        }
        // $this->display();
    
//******************************************************************************************************
    public function Finish(){
        layout('user');
        $this->assign('alipay',U('Alipay'));
        if(!is_null(I('get.orderid'))){
            $orderid=I('get.orderid');//订单号
            $user=M('myorder');
            $r=$user->where("id='{$orderid}'")->find();
            // print_r($r);
            // exit;
            // $this->assign('orderid',$orderid);
            $this->assign('goods',$r);
        }
        $this->display();
    }
    public function Alipay(){
        if(!is_null(I('get.orderid'))){
            $orderid=I('get.orderid');//传过来的订单ID
            $user=M('myorder');
            $r=$user->where("id='{$orderid}'")->find();

            include THINK_PATH."Library/Org/alipay/AopSdk.php";
            $alipay = new \AopClient;
            $alipay->gatewayUrl = "https://openapi.alipaydev.com/gateway.do";
            $alipay->appId = C('appId');
            $alipay->rsaPrivateKey = C('rsaPrivateKey');
            $alipay->format = C('format');
            $alipay->charset= C('charset');
            $alipay->signType= C('signType');
            $alipay->alipayrsaPublicKey = C('alipayrsaPublicKey');
            include THINK_PATH."Library/Org/Alipay/Aop/request/AlipayTradePagePayRequest.php";
            $request = new \AlipayTradePagePayRequest();
            $content="{" .
                "    \"out_trade_no\":\"".$r['id']."\"," .
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," .
                "    \"total_amount\":".$r['totalpay']."," .
                "    \"subject\":\"新安网店\"," .
                "    \"body\":\"新安网店\"," .
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," .
                "    \"extend_params\":{" .
                "    \"sys_service_provider_id\":\"2088511833207846\"" .
                "    }".
                "  }";
            $request->setBizContent($content);
            $request->setNotifyUrl(U('alipayNotify','',true,true));
            $request->setReturnUrl(U('alipayReturn','',true,true));
            $this->form = $alipay->pageExecute($request); //调用SDK生成表单
            $this->display();
            
        }else{
             $this->error("参数错误");
        }
    }

    public function alipayReturn(){
        //连接支付宝
        include THINK_PATH."Library/Org/alipay/AopSdk.php";
        $aop = new \AopClient();
        $alipayrsaPublicKey = C('alipayPublicKey');
        $signtype = C('signType');
        $aop->alipayrsaPublicKey = $alipayrsaPublicKey;
        $arr=$_GET;
        // var_dump($arr);
        $result = $aop->rsaCheckV1($arr,$alipayrsaPublicKey,$signtype);
        // var_dump($result);
        // exit;
        if($result){
            $order_id=$arr['out_trade_no'];
            if($order_id>0){
                $orderModel=M('myorder');
                //开启事务
                $orderModel->startTrans();
                //查询订单
                $order=$orderModel->lock(true)->find($order_id);
                // print_r($order);
                if($order&&$order['status']==0){//查找商品准备扣除库存
                    $go=M('goods_order');
                    $r=$go->where("order_id='{$order_id}'")->select();
                    // print_r($r);
                    // exit;
                    foreach ($r as $key => $value) {
                        $goods=M('goods');
                        $a=$value['goodsname'];
                        $re= $goods->lock(true)->where("goodsname='{$a}'")->find();//商品数组￥value订单数组
                        $stock=$re['stock']-$value['buynum'];
                        if($stock>0){
                            $newstock['stock']=$stock;//新的库存
                            $u=$goods->where("id=".$re['id'])->save($newstock);
                            if(!$u){//更新商品表成功
                                $orderModel->rollback();
                                echo $re['goodsname']."商品库存错误";
                            }
                        }else{
                            $orderModel->rollback();
                            echo $re['goodsname']."商品库存不足";
                        }
                    }


                    $orderstatus['status']=1;
                    $neworderstatus=$orderModel->where("id='{$order_id}'")->save($orderstatus);
                    if($neworderstatus){
                        $orderModel->commit();
                        echo '订单交易完成，请等待卖家发货';
                    }else{
                        $orderModel->rollback();
                        echo "更新订单表状态失败";
                    }


                }else{
                    echo "订单信息错误";
                }
            }
        }else{
            echo 'error';
        }
    }
}


//******************************************************************************************************
    // public function Buynow(){
    //     layout('user');
    //     $loginuser_id=$this->user_id;//登录时，保存的用户ID
    //     $this->assign('finishsave',U('Finishsave'));
    //     if(!is_null(I('get.goodsid'))){
    //         $goodsid=I('get.goodsid');//OK
    //         $user=M('goods');
    //         $r=$user->field('*,(select name from fm_photo where fm_goods.id=fm_photo.goods_id limit 1) as name ')->join('left join fm_buycar on fm_goods.id=fm_buycar.goods_id')->where("fm_goods.id='{$goodsid}'")->find();
    //         // print_r($r);
    //         // exit;
    //         $this->assign('goods',$r);
    //         $address=M('goodsuser');//收货地址表
    //         $addr=$address->where("loginuser_id='{$loginuser_id}'")->select();
    //         $this->assign('address',$addr);
    //     }
    //     $this->display();
    // }751923
// $this->orderid=I('get.orderid');//订单号
//             $this->ordercode=I('get.ordercode');//订单号
//             $this->totalpay=I('get.totalpay');//总价钱
//             $this->buyusername=I('get.buyusername');//收货人
//             $this->newaddress=I('get.newaddress');//收货地址
//             $user=M('goods_order');
